package com.tms.control;

import com.github.pagehelper.PageInfo;
import com.tms.domain.TDef;
import com.tms.domain.Tool;
import com.tms.domain.Type;
import com.tms.domain.User;
import com.tms.service.ToolDefService;
import com.tms.service.ToolService;
import com.tms.service.TypeService;
import com.tms.utils.Data;
import com.tms.utils.JsonResult;
import com.tms.utils.token.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.tms.core.constants.TDefConstants.*;

/**
 * 模具定义
 */
@RestController
@RequestMapping("/api/tDefs")
public class ToolDefController extends BaseController {

    @Autowired
    private ToolDefService toolDefService;

    @Autowired
    private ToolService toolService;

    @Autowired
    TypeService typeService;

    @Autowired
    private TokenService tokenService;

   /**
     * 根据ID更新
     */
    @PatchMapping("/{id}")
    public JsonResult updateById(@RequestBody Map<String, String> map, @PathVariable String id, HttpServletRequest req) {
        JsonResult result;
        //判断 workcellId 判断是否是同一部门
        User user = tokenService.getUserByRequest(req);
        //如果没有这个人
        if (user == null) {
            result = new JsonResult(ERROR_NULL_USER.getStatus(), ERROR_NULL_USER.getDesc());
        }
        //修改模具type类别
        else if (map.size() == 1) {
            Type type = typeService.findById(Integer.parseInt(id));
            String newName = map.get("type");
            if (newName == null || newName.isEmpty()) {
                result = new JsonResult(ERROR_NULL_NAME.getStatus(), ERROR_NULL_NAME.getDesc());
                return result;
            }
            type.setName(newName);
            typeService.updateById(type);
            type = typeService.findById(Integer.parseInt(id));
            result = new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(type));
        } else {
            //修改模具基本信息
            TDef toolDef = toolDefService.findToolDefById(Integer.parseInt(id));
            // 这里的toolDef需要判一下空，如果没有后面set的时候会报错
            if (toolDef == null) {
                result = new JsonResult(ERROR.getStatus(), ERROR.getDesc());
                return result;
            } else if (toolDef.getWorkcell().getId() != user.getWorkcell().getId()) {
                return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
            } else {
                String name = map.get("name");
                String partNo = map.get("partNo");
                String usedFor = map.get("usedFor");
                int upl = Integer.parseInt(map.get("upl"));
                if (name == null || partNo == null || usedFor == null || upl == 0) {
                    result = new JsonResult(ERROR_NULL_PARAMS.getStatus(), ERROR_NULL_PARAMS.getDesc());
                    return result;
                }
                toolDef.setName(name);
                toolDef.setPartNo(partNo);
                toolDef.setUsedFor(usedFor);
                toolDef.setUpl(upl);
                toolDefService.updateToolDefById(toolDef);
                //返回结果
                TDef toolDefVer = toolDefService.findToolDefById(Integer.parseInt(id));
                result = new JsonResult(SUCCESS.getStatus(), SUCCESS.getDesc(), new Data(toolDefVer));
            }
        }
        return result;
    }

    /**
     * 分页查看某一tDef下的所有tool
     *
     * @param id       tDef的id
     * @param page     页数
     * @param pageSize 每页个数
     * @return 成功返回相关的 tool 信息，失败返回错误信息
     */
    @GetMapping("/{id}/tools")
    public JsonResult viewToolDefs(@PathVariable(value = "id") int id, @RequestParam(value = "page", defaultValue = "1") int page,
                                   @RequestParam(value = "pageSize", defaultValue = "5") int pageSize, HttpServletRequest request) {
        //取出 workcellId 判断是否是同一部门
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult(ERROR_TOKEN.getStatus(), ERROR_TOKEN.getDesc());
        }
        TDef tDef = toolDefService.findToolDefById(id);
        //如果取出的 tDef 是空或者 与user 不在同一部门 或者 code 为空
        if (tDef == null) {
            return new JsonResult(ERROR_NULL_TDEF.getStatus(), ERROR_NULL_TDEF.getDesc());
        } else if (tDef.getCode() == null || tDef.getCode().isEmpty()) {
            return new JsonResult(ERROR_NULL_CODE_TDEF.getStatus(), ERROR_NULL_CODE_TDEF.getDesc());
        } else if (tDef.getWorkcell().getId() != workcellId) {
            return new JsonResult(ERROR_OTHER_WORKCELL.getStatus(), ERROR_OTHER_WORKCELL.getDesc());
        }
        PageInfo<Tool> tools = toolService.findToolsByCode(page, pageSize, tDef.getCode());
        return new JsonResult("success", "操作成功。", new Data("tools", tools));
    }

    /**
     * 查看某一确认的tDef
     *
     * @param id tDef的id
     * @return 成功返回tDef相关信息，失败返回错误信息
     */
    @GetMapping("/{id}")
    public JsonResult viewToolDef(@PathVariable(value = "id") int id, HttpServletRequest request) {
        //取出 workcellId 判断是否是同一部门
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult("failed", "token过期或者格式不正确，请重新获取token。");
        }
        TDef tDef = toolDefService.findToolDefById(id);
        //如果取出的 tDef 是空或者 与user 不在同一部门
        if (tDef == null) {
            return new JsonResult("failed", "不存在该toolDef，请核对是否存在该记录。");
        } else if (tDef.getWorkcell().getId() != workcellId) {
            return new JsonResult("failed", "不能操作其他workcell部门的信息。");
        }
        return new JsonResult("success", "操作成功。", new Data(tDef));
    }

    /**
     * 查找相应param类型的tDefs
     *
     * @param page     页数
     * @param pageSize 每页个数
     * @param param    查询类型，分别为 name, usedFor, code
     * @param content  查找内容
     * @param request  获取token以取得workcellId
     * @return 成功返回tDef相关信息，失败返回错误信息
     */
    @GetMapping
    public JsonResult findToolDefs(@RequestParam(value = "page", defaultValue = "1") int page,
                                   @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                   @RequestParam(value = "param", defaultValue = "") String param,
                                   @RequestParam(value = "content", defaultValue = "") String content,
                                   HttpServletRequest request) {
        int workcellId = tokenService.getWorkcellId(request);
        if (workcellId == 0) {
            return new JsonResult("failed", "token过期或者格式不正确，请重新获取token。");
        }
        PageInfo<TDef> info = toolDefService.findToolDefByContent(page, pageSize, param, content, workcellId);
        //如果取到的 info 为空
        if (info == null) {
            return new JsonResult("failed", "操作失败。");
        }
        return new JsonResult("success", "操作成功。", new Data("tDefs", info));
    }
}